package cn.com.inossem.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.WindowManager;
import android.widget.ImageView;
import cn.com.inossem.config.WSConfig;

/**
 * ���߻�ȡͼƬ
 * 
 * @author ��Ӣ��
 * 
 */
public class AsyncImageLoader {
	public Context context;
	//private HashMap<String, SoftReference<Drawable>> imageCache;
	public static String imgpath = "sdcard/sapapp/";

	public AsyncImageLoader(Context context) {
		this.context = context;

		//imageCache = new HashMap<String, SoftReference<Drawable>>();
	}

	/**
	 * ����ͼƬ �ⲿ�������
	 * 
	 * @param imageUrl
	 * @param imageCallback
	 * @return
	 */
	public Drawable loadDrawable(final String imageUrl,
			final ImageCallback imageCallback) {
//		if (imageCache.containsKey(imageUrl)) {
//			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
//			Drawable drawable = softReference.get();
//			if (drawable != null) {
//				return drawable;
//			}
//		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
			}
		};
		new Thread() {
			@Override
			public void run() {
				Drawable drawable = loadImageFromUrl(imageUrl);
				//imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}

	/**
	 * ����·������ͼƬ����
	 * 
	 * @param url
	 * @return
	 */
	public Drawable loadImageFromUrl(String url) {
		// ��ѯ����
		File f = new File(imgpath
				+ url.replace(WSConfig.IMAGE_URL, "").replace("/", ""));
		if (f.exists()) {
			String path = imgpath
					+ url.replace(WSConfig.IMAGE_URL, "").replace("/", "");
			// return Drawable.createFromPath(imgpath
			// + url.replace(WSConfig.IMAGE_URL, "").replace("/", ""));
			BitmapFactory.Options opts = new Options();
			// 不读取像素数组到内存中，仅读取图片的信息
			opts.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(path, opts);
			// 从Options中获取图片的分辨率
			int imageHeight = opts.outHeight;
			int imageWidth = opts.outWidth;
			// 获取Android屏幕的服务
			WindowManager wm = (WindowManager) context
					.getSystemService(context.WINDOW_SERVICE);
			// 获取屏幕的分辨率，getHeight()、getWidth已经被废弃掉了
			// 应该使用getSize()，但是这里为了向下兼容所以依然使用它们
			int windowHeight = wm.getDefaultDisplay().getHeight();
			int windowWidth = wm.getDefaultDisplay().getWidth();
			// 计算采样率
			int scaleX = imageWidth / windowWidth;
			int scaleY = imageHeight / windowHeight;
			int scale = 1;
			// 采样率依照最大的方向为准
			if (scaleX > scaleY && scaleY >= 1) {
				scale = scaleX;
			}
			if (scaleX < scaleY && scaleX >= 1) {
				scale = scaleY;
			}
			// false表示读取图片像素数组到内存中，依照设定的采样率
			opts.inJustDecodeBounds = false;
			// 采样率
			opts.inSampleSize = scale;
			Bitmap bitmap = BitmapFactory.decodeFile(path, opts);
			Drawable drawable = new BitmapDrawable(bitmap);
			return drawable;
		} else {
			URL m;
			InputStream i = null;
			Drawable d = null;
			try {
				m = new URL(url);
				System.out.println(url);
				i = (InputStream) m.getContent();
				d = Drawable.createFromStream(i, "src");
//				d = decodeFile(i);
				i.close();
				Utils.savePic(((BitmapDrawable) d).getBitmap(),
						url.replace(WSConfig.IMAGE_URL, "").replace("/", ""));
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (null != i) {
					try {
						i.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

			return d;
		}

	}
	
	private Drawable decodeFile(InputStream input) {
            // Decode image size
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(input, null, opts);
            opts.inSampleSize = computeSampleSize(opts, -1, 128 * 128);  
            opts.inJustDecodeBounds = false;  
            Bitmap bmp = BitmapFactory.decodeStream(input, null, opts);
                ImageView iv = new ImageView(context);
                iv.setImageBitmap(bmp);
                return iv.getDrawable();
    }
	
	public static int computeSampleSize(BitmapFactory.Options options,  
	        int minSideLength, int maxNumOfPixels) {  
	    int initialSize = computeInitialSampleSize(options, minSideLength,  
	            maxNumOfPixels);  
	    int roundedSize;  
	    if (initialSize <= 8) {  
	        roundedSize = 1;  
	        while (roundedSize < initialSize) {  
	            roundedSize <<= 1;  
	        }  
	    } else {  
	        roundedSize = (initialSize + 7) / 8 * 8;  
	    }  
	    return roundedSize;  
	}  
	  
	private static int computeInitialSampleSize(BitmapFactory.Options options,  
	        int minSideLength, int maxNumOfPixels) {  
	    double w = options.outWidth;  
	    double h = options.outHeight;  
	    int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math  
	            .sqrt(w * h / maxNumOfPixels));  
	    int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(  
	            Math.floor(w / minSideLength), Math.floor(h / minSideLength));  
	    if (upperBound < lowerBound) {  
	        // return the larger one when there is no overlapping zone.  
	        return lowerBound;  
	    }  
	    if ((maxNumOfPixels == -1) && (minSideLength == -1)) {  
	        return 1;  
	    } else if (minSideLength == -1) {  
	        return lowerBound;  
	    } else {  
	        return upperBound;  
	    }  
	} 

	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}
}